package com.jy.datapipeline.export.quartz;

import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class InitJobExecute {

    @Autowired
    private Scheduler scheduler;
    @Value("${config.localStorePath}")
    private String  localStorePath;
    private  void initTaskStatusByErrorHandler() throws SchedulerException {

        String taskId="export_task_status_by_error";

        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
        if(scheduler.getTrigger(triggerKey)==null){

        JobDetail jobDetail = JobBuilder.newJob(JobDetailTaskStatusByErrorHandler.class)
            .withIdentity(taskId).build();
        //通过指定开始时间和cron表达式,创建触发器
        Trigger trigger = TriggerBuilder.newTrigger()
            .withIdentity(taskId)
            .withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?")
                //如果cron表达式指定的时间错过了当前的这个时间点就会忽略，等待下一次到达这个时间点执行
                .withMisfireHandlingInstructionDoNothing()).build();

        //关联触发器和任务
        scheduler.scheduleJob(jobDetail, trigger);


        }else {
            log.info("quartz init taskname: {}",triggerKey.getName());
            if(triggerState.name().equals(TriggerState.ERROR.name())){
                JobKey jobKey = scheduler.getTrigger(triggerKey).getJobKey();
                scheduler.triggerJob(jobKey);
                log.info("task current is error, restry load");
            }
        }
    }

    private  void initTaskStatusBySuccessHandler() throws SchedulerException {
        String taskId = "export_task_status_by_success";
        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
        if (scheduler.getTrigger(triggerKey)==null) {
            JobDetail jobDetail = JobBuilder.newJob(JobDetailTaskStatusBySuccessHandler.class)
                .withIdentity(taskId).build();
            //通过指定开始时间和cron表达式,创建触发器
            Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskId)
                .withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?")
                    //如果cron表达式指定的时间错过了当前的这个时间点就会忽略，等待下一次到达这个时间点执行
                    .withMisfireHandlingInstructionDoNothing()).build();
        //关联触发器和任务
        scheduler.scheduleJob(jobDetail, trigger);
     }else{
            log.info("quartz init taskname: {}",triggerKey.getName());
            if(triggerState.name().equals(TriggerState.ERROR.name())){
                JobKey jobKey = scheduler.getTrigger(triggerKey).getJobKey();
                scheduler.triggerJob(jobKey);
                log.info("task current is error, restry load");
            }
        }
    }

    private  void initTaskRestryFileToSftpHandler() throws SchedulerException {
        String taskId="export_task_restry_file_to_sftp";
        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
        if (scheduler.getTrigger(triggerKey)==null) {
            JobDetail jobDetail = JobBuilder.newJob(JobDetailRestryFileToSftpHandler.class)
                .withIdentity(taskId).build();
            //通过指定开始时间和cron表达式,创建触发器
            Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskId)
                .withSchedule(CronScheduleBuilder.cronSchedule("0 */1  * * * ?")
                    //如果cron表达式指定的时间错过了当前的这个时间点就会忽略，等待下一次到达这个时间点执行
                    .withMisfireHandlingInstructionDoNothing()).build();

            //关联触发器和任务
            scheduler.scheduleJob(jobDetail, trigger);
        }else{
            log.info("quartz init taskname: {}",triggerKey.getName());
            if(triggerState.name().equals(TriggerState.ERROR.name())){
                JobKey jobKey = scheduler.getTrigger(triggerKey).getJobKey();
                scheduler.triggerJob(jobKey);
                log.info("task current is error, restry load");
            }
        }
    }

    private  void initTaskCheckFeedBackHandler() throws SchedulerException {
        String taskId="export_task_check_feed_back";
        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);
        if (scheduler.getTrigger(triggerKey)==null) {
            JobDetail jobDetail = JobBuilder.newJob(JobDetailCheckFeedBackHandler.class)
                .withIdentity(taskId).build();
            //通过指定开始时间和cron表达式,创建触发器
            Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskId)
                .withSchedule(CronScheduleBuilder.cronSchedule("0 */10 * * * ?")
                    //如果cron表达式指定的时间错过了当前的这个时间点就会忽略，等待下一次到达这个时间点执行
                    .withMisfireHandlingInstructionDoNothing()).build();

            //关联触发器和任务
            scheduler.scheduleJob(jobDetail, trigger);
        }else{
            log.info("quartz init taskname: {}",triggerKey.getName());
            if(triggerState.name().equals(TriggerState.ERROR.name())){
                JobKey jobKey = scheduler.getTrigger(triggerKey).getJobKey();
                scheduler.triggerJob(jobKey);
                log.info("task current is error, restry load");
            }
        }
    }

    private  void initTaskGetVerifyHandler() throws SchedulerException {
        String taskId="export_task_get_verify";
//        scheduler.pauseJob(JobKey.jobKey(taskId));
//        scheduler.deleteJob(JobKey.jobKey(taskId));

        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        scheduler.pauseTrigger(triggerKey);// 停止触发器
        scheduler.unscheduleJob(triggerKey);// 移除触发器
        scheduler.deleteJob(JobKey.jobKey(taskId));// 删除任务


        //TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);

        if (scheduler.getTrigger(triggerKey)==null) {
            JobDetail jobDetail = JobBuilder.newJob(JobDetailGetVerifyHandler.class)
                .withIdentity(taskId).build();
            jobDetail.getJobDataMap().put("localStorePath",localStorePath);
            //通过指定开始时间和cron表达式,创建触发器
            Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskId)
                .withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?")
                    //如果cron表达式指定的时间错过了当前的这个时间点就会忽略，等待下一次到达这个时间点执行
                    .withMisfireHandlingInstructionDoNothing()).build();

            //关联触发器和任务
            scheduler.scheduleJob(jobDetail, trigger);
        }else{
            log.info("quartz init taskname: {}",triggerKey.getName());
            if(triggerState.name().equals(TriggerState.ERROR.name())){
                JobKey jobKey = scheduler.getTrigger(triggerKey).getJobKey();
                scheduler.triggerJob(jobKey);
                log.info("task current is error, restry load");
            }
        }
    }

    @PostConstruct
    private  void  initscheduleJobs(){
        try {
            initTaskStatusByErrorHandler();
            initTaskStatusBySuccessHandler();
            initTaskRestryFileToSftpHandler();
            initTaskCheckFeedBackHandler();
            initTaskGetVerifyHandler();
        }catch (Exception e){
                log.error("export init scheduleJobs error",e);
        }

    }
}
